/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Serial;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
/**
 *
 * @author senior_design
 */
public class Serial {
    
    private static Enumeration	      portList;
    private static CommPortIdentifier portId;
    private static byte[] part1x10 = new byte[4];
    private static byte[] part2x10 = new byte[4];
    private static SerialPort	      serialPort;
    private static OutputStream       outputStream;
    private static boolean	      outputBufferEmptyFlag = false;
    
    private static byte[] houseCode = {96, (byte) 224, 32, (byte) 160, 16, 
        (byte)144, 80, (byte) 208, 112, (byte) 240, 48, (byte) 176, 0, 
        (byte) 128, 64, (byte) 192};
    private static byte[] deviceCode = {6, 14, 2, 10, 1, 9, 5, 13, 7, 15, 3, 11,
        0, 8, 4, 12};
    private boolean portFound;
    private String  defaultPort = "COM3";
    
    public Serial()
    {
        portFound = false;
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
	    portId = (CommPortIdentifier) portList.nextElement();

	    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

		if (portId.getName().equals(defaultPort)) {
		    System.out.println("Found port " + defaultPort);

		    portFound = true;
                }
            }
        }   
    }
    
    public void xOn(char house, int device)
    {
        part1x10[0] = 2;
        part1x10[1] = 99;
        part1x10[2] = (byte) (houseCode[houseToInt(house)] + deviceCode[device-1]);
        part1x10[3] = 0;
        
        part2x10[0] = 2;
        part2x10[1] = 99;
        part2x10[2] = (byte) (houseCode[houseToInt(house)] + 2);
        part2x10[3] = (byte) 128;
        
        if(portFound)
        {
            try {
			serialPort = 
			    (SerialPort) portId.open("SimpleWrite", 2000);
		    } catch (PortInUseException e) {
			System.out.println("Port in use.");

			//continue;
		    } 

		    try {
			outputStream = serialPort.getOutputStream();
		    } catch (IOException e) {}

		    try {
			serialPort.setSerialPortParams(19200, 
						       SerialPort.DATABITS_8, 
						       SerialPort.STOPBITS_1, 
						       SerialPort.PARITY_NONE);
		    } catch (UnsupportedCommOperationException e) {}
	

		    try {
		    	serialPort.notifyOnOutputEmpty(true);
		    } catch (Exception e) {
			System.out.println("Error setting event notification");
			System.out.println(e.toString());
			System.exit(-1);
		    }
		    try {
			outputStream.write(part1x10);
		    } catch (IOException e) {}

		    try {
		       Thread.sleep(500);  // Be sure data is xferred before closing
		    } catch (Exception e) {}
                    
                    try {
			outputStream.write(part2x10);
		    } catch (IOException e) {}

		    try {
		       Thread.sleep(500);  // Be sure data is xferred before closing
		    } catch (Exception e) {}
		    serialPort.close();
		    //System.exit(1);
        }
    }
    
    public void xOff(char house, int device)
    {
        part1x10[0] = 2;
        part1x10[1] = 99;
        part1x10[2] = (byte) (houseCode[houseToInt(house)] + deviceCode[device-1]);
        part1x10[3] = 0;
        
        part2x10[0] = 2;
        part2x10[1] = 99;
        part2x10[2] = (byte) (houseCode[houseToInt(house)] + 3);
        part2x10[3] = (byte) 128;
        
        
        
        if(portFound)
        {
            try {
			serialPort = 
			    (SerialPort) portId.open("SimpleWrite", 2000);
		    } catch (PortInUseException e) {
			System.out.println("Port in use.");

			//continue;
		    } 

		    try {
			outputStream = serialPort.getOutputStream();
		    } catch (IOException e) {}

		    try {
			serialPort.setSerialPortParams(19200, 
						       SerialPort.DATABITS_8, 
						       SerialPort.STOPBITS_1, 
						       SerialPort.PARITY_NONE);
		    } catch (UnsupportedCommOperationException e) {}
	

		    try {
		    	serialPort.notifyOnOutputEmpty(true);
		    } catch (Exception e) {
			System.out.println("Error setting event notification");
			System.out.println(e.toString());
			System.exit(-1);
		    }
		    try {
			outputStream.write(part1x10);
		    } catch (IOException e) {}

		    try {
		       Thread.sleep(500);  // Be sure data is xferred before closing
		    } catch (Exception e) {}
                    
                    try {
			outputStream.write(part2x10);
		    } catch (IOException e) {}

		    try {
		       Thread.sleep(500);  // Be sure data is xferred before closing
		    } catch (Exception e) {}
		    serialPort.close();
		    //System.exit(1);
        }
    }
    
    public void dim(char house, int device)
    {
        part1x10[0] = 2;
        part1x10[1] = 99;
        part1x10[2] = (byte) (houseCode[houseToInt(house)] + deviceCode[device-1]);
        part1x10[3] = 0;
        
        part2x10[0] = 2;
        part2x10[1] = 99;
        part2x10[2] = (byte) (houseCode[houseToInt(house)] + 4);
        part2x10[3] = (byte) 128;
        
        
        
        if(portFound)
        {
            try {
			serialPort = 
			    (SerialPort) portId.open("SimpleWrite", 2000);
		    } catch (PortInUseException e) {
			System.out.println("Port in use.");

			//continue;
		    } 

		    try {
			outputStream = serialPort.getOutputStream();
		    } catch (IOException e) {}

		    try {
			serialPort.setSerialPortParams(19200, 
						       SerialPort.DATABITS_8, 
						       SerialPort.STOPBITS_1, 
						       SerialPort.PARITY_NONE);
		    } catch (UnsupportedCommOperationException e) {}
	

		    try {
		    	serialPort.notifyOnOutputEmpty(true);
		    } catch (Exception e) {
			System.out.println("Error setting event notification");
			System.out.println(e.toString());
			System.exit(-1);
		    }
		    try {
			outputStream.write(part1x10);
		    } catch (IOException e) {}

		    try {
		       Thread.sleep(500);  // Be sure data is xferred before closing
		    } catch (Exception e) {}
                    
                    try {
			outputStream.write(part2x10);
		    } catch (IOException e) {}

		    try {
		       Thread.sleep(500);  // Be sure data is xferred before closing
		    } catch (Exception e) {}
		    serialPort.close();
		    //System.exit(1);
        }
    }
    
    public void bright(char house, int device)
    {
        part1x10[0] = 2;
        part1x10[1] = 99;
        part1x10[2] = (byte) (houseCode[houseToInt(house)] + deviceCode[device-1]);
        part1x10[3] = 0;
        
        part2x10[0] = 2;
        part2x10[1] = 99;
        part2x10[2] = (byte) (houseCode[houseToInt(house)] + 5);
        part2x10[3] = (byte) 128;
        
        
        
        if(portFound)
        {
            try {
			serialPort = 
			    (SerialPort) portId.open("SimpleWrite", 2000);
		    } catch (PortInUseException e) {
			System.out.println("Port in use.");

			//continue;
		    } 

		    try {
			outputStream = serialPort.getOutputStream();
		    } catch (IOException e) {}

		    try {
			serialPort.setSerialPortParams(19200, 
						       SerialPort.DATABITS_8, 
						       SerialPort.STOPBITS_1, 
						       SerialPort.PARITY_NONE);
		    } catch (UnsupportedCommOperationException e) {}
	

		    try {
		    	serialPort.notifyOnOutputEmpty(true);
		    } catch (Exception e) {
			System.out.println("Error setting event notification");
			System.out.println(e.toString());
			System.exit(-1);
		    }
		    try {
                        for(int j =0;j<part1x10.length;j++){
                                    System.out.print(Integer.toHexString(part1x10[j]&0xFF)+" ");}
			outputStream.write(part1x10);
		    } catch (IOException e) {}

		    try {
		       Thread.sleep(500);  // Be sure data is xferred before closing
		    } catch (Exception e) {}
                    
                    try {
                        for(int j =0;j<part2x10.length;j++){
                                    System.out.print(Integer.toHexString(part2x10[j]&0xFF)+" ");}
			outputStream.write(part2x10);
		    } catch (IOException e) {}

		    try {
		       Thread.sleep(500);  // Be sure data is xferred before closing
		    } catch (Exception e) {}
		    serialPort.close();
		    //System.exit(1);
        }
    }
    
    private int houseToInt(char house)
    {
        int houseAsNum=16;
        switch(house){
            case 'A': houseAsNum=0;
                    break;
            case 'B': houseAsNum=1;
                    break;
            case 'C': houseAsNum=2;
                    break;
            case 'D': houseAsNum=3;
                    break;
            case 'E': houseAsNum=4;
                    break;
            case 'F': houseAsNum=5;
                    break;
            case 'G': houseAsNum=6;
                    break;
            case 'H': houseAsNum=7;
                    break;
            case 'I': houseAsNum=8;
                    break;
            case 'J': houseAsNum=9;
                    break;
            case 'K': houseAsNum=10;
                    break;
            case 'L': houseAsNum=11;
                    break;
            case 'M': houseAsNum=12;
                    break;
            case 'N': houseAsNum=13;
                    break;
            case 'O': houseAsNum=14;
                    break;
            case 'P': houseAsNum=15;
                    break;
        }
        return houseAsNum;
                
    }
    
    }
    
    
//    public static void main(String[] args) {
//        //
//        HashSet <CommPortIdentifier>collection = getAvailableSerialPorts();
//        Iterator iterator = collection.iterator(); 
//        while (iterator.hasNext()){
//        System.out.print(iterator.next() + " ");  
//        }
//        System.out.println();
//        // Get size of a collection
//        
//        if (collection.isEmpty()){
//        System.out.println("Collection is empty");
//        }
//        else{
//        System.out.println( "Collection size: " + collection.size());
//        }
//        
//        byte test = 1;
//        System.out.println(test);
//        
//        
//        
//        
//        
//    }
//    
//    public static HashSet<CommPortIdentifier> getAvailableSerialPorts() {
//        HashSet<CommPortIdentifier> h = new HashSet<CommPortIdentifier>();
//        Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
//        while (thePorts.hasMoreElements()) {
//            CommPortIdentifier com = (CommPortIdentifier) thePorts.nextElement();
//            switch (com.getPortType()) {
//            case CommPortIdentifier.PORT_SERIAL:
//                try {
//                    CommPort thePort = com.open("CommUtil", 50);
//                    thePort.close();
//                    System.out.println(com.getName());
//                    h.add(com);
//                } catch (PortInUseException e) {
//                    System.out.println("Port, "  + com.getName() + ", is in use.");
//                } catch (Exception e) {
//                    System.err.println("Failed to open port " +  com.getName());
//                    e.printStackTrace();
//                }
//            }
//        }
//        return h;
//    }
//    
//}

// BEAK COMMENT IT WORKED BELOW HERE!
    
//        static Enumeration	      portList;
//    static CommPortIdentifier portId;
////    static String	      messageString = "02993000";
////    static String	      messageString2 = "029918";
//    static byte[] buffer = new byte[4];
//    static byte[] buffer2 = new byte[4];
//    static SerialPort	      serialPort;
//    static OutputStream       outputStream;
//    static boolean	      outputBufferEmptyFlag = false;
//    /**
//     * Method declaration
//     *
//     *
//     * @param args
//     *
//     * @see
//     */
//    public static void main(String[] args) {
//	boolean portFound = false;
//	String  defaultPort = "COM3";
//
//	if (args.length > 0) {
//	    defaultPort = args[0];
//	} 
//        
//        buffer[0]=2;
//        buffer[1]=99;
//        buffer[2]=0x16;
//        buffer[3]=0;
//        buffer2[0]=2;
//        buffer2[1]=99;
//        buffer2[2]=19;
//        buffer2[3]=(byte) 128;
//        
//	portList = CommPortIdentifier.getPortIdentifiers();
//
//	while (portList.hasMoreElements()) {
//	    portId = (CommPortIdentifier) portList.nextElement();
//
//	    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
//
//		if (portId.getName().equals(defaultPort)) {
//		    System.out.println("Found port " + defaultPort);
//
//		    portFound = true;
//
//		    try {
//			serialPort = 
//			    (SerialPort) portId.open("SimpleWrite", 2000);
//		    } catch (PortInUseException e) {
//			System.out.println("Port in use.");
//
//			continue;
//		    } 
//
//		    try {
//			outputStream = serialPort.getOutputStream();
//		    } catch (IOException e) {}
//
//		    try {
//			serialPort.setSerialPortParams(19200, 
//						       SerialPort.DATABITS_8, 
//						       SerialPort.STOPBITS_1, 
//						       SerialPort.PARITY_NONE);
//		    } catch (UnsupportedCommOperationException e) {}
//	
//
//		    try {
//		    	serialPort.notifyOnOutputEmpty(true);
//		    } catch (Exception e) {
//			System.out.println("Error setting event notification");
//			System.out.println(e.toString());
//			System.exit(-1);
//		    }
//		    
//		    
////		    System.out.println(
////		    	"Writing \""+messageString+"\" to "
////			+serialPort.getName());
//
//		    try {
//			outputStream.write(buffer);
//		    } catch (IOException e) {}
//
//		    try {
//		       Thread.sleep(2000);  // Be sure data is xferred before closing
//		    } catch (Exception e) {}
//                    
//                    try {
//			outputStream.write(buffer2);
//		    } catch (IOException e) {}
//
//		    try {
//		       Thread.sleep(2000);  // Be sure data is xferred before closing
//		    } catch (Exception e) {}
//		    serialPort.close();
//		    System.exit(1);
//		} 
//	    } 
//	} 
//
//	if (!portFound) {
//	    System.out.println("port " + defaultPort + " not found.");
//	} 
//    } 
//
//
//}
